
package cartagows.wsframework.wssecurity.policy.model;

import java.util.ArrayList;
import java.util.Iterator;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

import org.apache.neethi.PolicyComponent;

import cartagows.wsframework.wssecurity.policy.SP11Constants;
import cartagows.wsframework.wssecurity.policy.SP12Constants;
import cartagows.wsframework.wssecurity.policy.SPConstants;

public class RequiredParts extends AbstractSecurityAssertion {
    
    private ArrayList headers = new ArrayList();
    
    public RequiredParts(int version) {
        setVersion(version);
    }

    public ArrayList getHeaders() {
        return this.headers;
    }

    public void addHeader(Header header) {
        this.headers.add(header);
    }


    public QName getName() {
         return SP12Constants.REQUIRED_PARTS;         
    }

    public PolicyComponent normalize() {
        return this;
    }

    public void serialize(XMLStreamWriter writer) throws XMLStreamException {
        String localName = getName().getLocalPart();
        String namespaceURI = getName().getNamespaceURI();

        String prefix = writer.getPrefix(namespaceURI);

        if (prefix == null) {
            prefix = getName().getPrefix();
            writer.setPrefix(prefix, namespaceURI);
        }
            
        // <sp:RequiredParts> 
        writer.writeStartElement(prefix, localName, namespaceURI);
        
        // xmlns:sp=".."
        writer.writeNamespace(prefix, namespaceURI);
        
        Header header;        
        for (Iterator iterator = headers.iterator(); iterator.hasNext();) {
            header = (Header) iterator.next();
            // <sp:Header Name=".." Namespace=".." />
            writer.writeStartElement(prefix, SPConstants.HEADER, namespaceURI);
            // Name attribute is optional
            if (header.getName() != null) {
                writer.writeAttribute("Name", header.getName());
            }
            writer.writeAttribute("Namespace", header.getNamespace());
            
            writer.writeEndElement();
        }
        
        // </sp:RequiredParts>
        writer.writeEndElement();
    }    
    
    
}
